import axios from 'axios'
import { config } from './config'
import { getToken } from "../common/js/cache";

export class Http {
    static async get ({ url, data, token = getToken() } = {}) {
        const headers = await Http._isToken(token)
        url = `${config.apiBaseUrl}${url}`
        return new Promise((resolve, reject) => {
            axios.get(url,{
                params: data,
                headers
            }).then(res => {
                resolve(res.data)
            }, e => {
                reject(e)
            })
        })
    }

    static async post({url, data, token = getToken()} = {}) {
        const headers = await Http._isToken(token)
        url = `${config.apiBaseUrl}${url}`
        return new Promise((resolve, reject) => {
            axios.post(url, data, {
                headers
            }).then(res => {
                if (res.status === 200) {
                    resolve(res.data)
                }
            }, e => {
                reject(e)
            })
        })
    }

    static _isToken (token) {
        let header = {}
        return new Promise(resolve => {
            if (token == null) {
                resolve(header)
                return
            }
            header.Token = token
            resolve(header)
        })
    }

    static async upload({url, data}, progressEvent) {
        return new Promise((resolve, reject) => {
            axios.post(url, data, {
                headers: {
                    token: getToken(),
                    'Content-Type': 'multipart/form-data'
                },
                onUploadProgress: progressEvent
            }).then(res => {
                if (res.status === 200) {
                    resolve(res.data)
                }
            }, e => {
                reject(e)
            })
        })
    }

    static getUploadInfo (path, folderId) {
        folderId || (folderId = '')
        const urlList = {
            'private': `${config.apiBaseUrl}/UserFileUpload/${folderId}`,
            'public': `${config.apiBaseUrl}/uploadPublicFile`
        }
        return urlList[path]
    }
}
